﻿<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>添加商品到购物车</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />
<script type="application/x-javascript"> 
	//scrollTo() 方法可把内容滚动到指定的坐标
	addEventListener("load", 
		function() { setTimeout(hideURLbar, 0); }, false);
		function hideURLbar(){ window.scrollTo(0,1); }
		
</script>
<style type="">
	span {
		display: inline-block; /* 使得按钮水平排列 */
		margin-right: 10px; /* 按钮之间的间距 */
	}

	button {
		background-color: #4CAF50; /* 背景颜色 */
		color: white; /* 文字颜色 */
		padding: 10px 20px; /* 按钮内边距 */
		font-size: 16px; /* 文字大小 */
		border: none; /* 移除边框 */
		cursor: pointer; /* 鼠标指针样式 */
	}

	button:hover {
		background-color: #45a049; /* 鼠标悬停时的背景颜色 */
	}
	.top-seller {
		border: 4px solid gold; /* 金色边框 */
	}
	.discount-label{
		font-weight: bold;
		color: red; /* 红色字体表示突出显示 */
		margin-left: 10px; /* 添加一点间距 */
		font-size: 1.2em; /* 增大字号 */
	}
	.top-rank-label {
		font-weight: bold;
		color: gold; /* 红色字体表示突出显示 */
		margin-left: 10px; /* 添加一点间距 */
		font-size: 1.2em; /* 增大字号 */
	}
	.sales-num {
		color: #ffffff;
	}

	/* 购物车条目样式 */
	.cart-item-info {
		display: flex;
		align-items: center;
		justify-content: space-between; /* 这样可以使内容在横向上分布均匀 */
		margin-bottom: 10px; /* 给每个条目添加底部间距 */
	}

	.cart-item-info a {
		width: 100px;
		margin-right: 10px; /* 给链接添加右侧间距 */
	}

	.cart-item-info input[type="button"],
	.cart-item-info input[type="text"] {
		height: 25px; /* 设置按钮和文本框的高度 */
		vertical-align: middle; /* 垂直居中对齐 */
	}

	.cart-button {
		background-color: rgb(66 183 180); /* 按钮背景颜色 */
		color: white;
		border: 1px solid #ccc; /* 按钮边框 */
		border-radius: 10px;/*圆角*/
		cursor: pointer; /* 鼠标悬浮时显示指针 */
	}

	.cart-button:hover {
		background-color: rgba(66, 183, 173, 0.96); /* 鼠标悬浮时的背景颜色 */
	}

	.input-buynum {
		text-align: center; /* 文本居中 */
		margin: 0 5px; /* 文本框与按钮之间的间距 */
		background-color: rgb(66 183 180); /* 按钮背景颜色 */
		color: white;
		border-radius: 10px;/*圆角*/
		border: 0;
	}
	ul.cart-items {
		list-style-type: none; /* 移除列表项前的点 */
		padding-left: 0; /* 移除默认的左填充，使内容更靠左对齐 */
	}
	.cart-item-price{
		margin: 5px;
	}
	.cart-item-price a{
		color: red;
	}
.cart-item-foodname{
	color: rgb(0, 0, 0);
	font-size: 20px;
}

</style>
<!-- Custom Theme files -->
<link href="../css/app/bootstrap.css" type="text/css" rel="stylesheet" media="all">
<link href="../css/app/style.css" type="text/css" rel="stylesheet" media="all">  
<!-- //Custom Theme files --> 
<!-- js -->
<script src="../js/jquery-2.2.3.min.js"></script>
	<script src="../js/axios.js">
	</script><script src="../js/vue.js"></script>
<!-- //js -->
</head>
<body>
<div id="app"><!-- banner -->
	<div class="banner about-w3bnr">
		<!-- header -->
		<div class="header">
			<!-- //header-one -->
			<!-- navigation -->
			<div class="navigation agiletop-nav">
				<div class="container" style="margin-right: 5px;margin-left: 5px;">
					<nav class="navbar navbar-default">
						<!-- Brand and toggle get grouped for better mobile display -->
						<div class="navbar-header w3l_logo">
							<h1><a href="index.html">重生之我要做点菜系统</a></h1>
						</div>
						<div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
							<ul class="nav navbar-nav navbar-right">
								<li><a href="index.html" class="active">主页</a></li>
								<!-- Mega Menu -->
								<li>
									<a href="menu.html" class="dropdown-toggle" >菜单 </a>
								</li>
								<li class="w3pages">
									<a href="orderList.html" class="dropdown-toggle">我的订单</a>
								</li>

								<li class="head-dpdn">
									<a href="login.html">登录</a>
								</li>
								<li class="head-dpdn">
									<a href="register.html">免费注册</a>
								</li>
								<li class="head-dpdn">
									<a href="http://60.205.91.68:8080/admin/admin/pages/member/chat/userchat.html" target="_blank">客服</a>
								</li>
								<li class="head-dpdn">
									<a href="../html/login.html">退出</a>
								</li>
							</ul>
						</div>
					</nav>
				</div>
			</div>
			<!-- //navigation -->
		</div>
		<!-- //header-end -->
	</div>
	<!-- //banner -->
	<!-- breadcrumb -->
	<!-- //breadcrumb -->
	<!-- products -->

	<div class="products">
		<div class="container">
			<div class="col-md-9 product-w3ls-right" style="width: 70%;">

				<div id="foodType">
					<div class="product-top">
						<h4>主页/菜单:
							<span v-for="(type,index) in foodType" :key="index">
<!--					<a :href="'menu.html?foodTypeId=' + type.id" style="color:white;" v-model="foodTypeId">{{type.type_name}}</a>&nbsp;-->
									<button @click="updateTypeId(type.id)">{{type.type_name}}</button>
					</span>
						</h4>
						<div class="clearfix"></div>
					</div>
				</div>

				<!-- 右侧展示菜品开始 -->
				<div id="food">
					<div class="products-row">

						<div v-for="(food, index) in filteredFoods" :key="index" class="col-xs-6 col-sm-4 product-grids">
							<div class="flip-container" :class="{ 'top-seller': topSellingFoods.some(item => item.id === food.id) }">
								<div class="flipper agile-products">
									<div class="front">
										<img :src="food.img" style="width: 250px;height: 150px" class="img-responsive" alt="img">
										<div class="agile-product-text">
											<h5>{{ food.food_name }}</h5>
											<p class="sales-num">销量:{{ food.totalbuynum }}
												<span class="discount-label" v-if="food.discount!==1">{{food.discount*10}}折</span>
												<span v-if="topSellingFoods.some(item => item.id === food.id)" class="top-rank-label">
													Top {{ topSellingFoods.find(item => item.id === food.id).rank }}
												</span>
											</p>
										</div>
									</div>
									<div class="back">
										<h3>{{ food.food_name }}</h3>
										<p>{{ food.remark }}</p>
										<h6>{{ food.price }}<sup>￥</sup></h6>
										<form action="#" method="post">
											<input type="hidden" id="dinnerId" name="dinnerId" value="4">
											<button type="button" @click="addToCart(food.id)" class="w3ls-cart pw3ls-cart">
												<i class="fa fa-cart-plus" aria-hidden="true"></i>加入购物车
											</button>
											<span class="w3-agile-line"> </span>
											<a href="fooddetail.html" @click="fooddetail(food.id)">详情</a>
										</form>
									</div>
								</div>
							</div>
						</div>



					</div>
					<!-- 右侧展示菜品结束 -->
				</div>
			</div>


			<!-- 购物车 -->
			<div id="cart">
				<div class="col-md-3 rsidebar">
					<div class="rsidebar-top">
						<div class="sidebar-row">
							<ol class="breadcrumb w3l-crumbs">
								<li class="active">{{ dinnerTableId | showTable }}</li>
							</ol>
							<form method="post" action="" style="margin-left: -15px;width: 289px;margin-top: 10px;">
								<ul class="cart-items">
									<!-- 购物车条目 -->
									<li v-for="(food, index) in items" :key="index" class="cart-item">
										<div class="cart-item-info">
											<a href="fooddetail.html" class="cart-item-foodname">{{ food.name }}</a>
											<input name="id" :value="food.id" type="hidden">
											<input name="buyNum"  class="input-buynum" v-model="food.count" style="width: 30px;">
											<input type="button" value="-" @click="subCount(food)" class="cart-button">
											<input type="button" value="+" @click="addCount(food)" class="cart-button">
											<input type="button" value="移除" @click="removeItem(food)" class="cart-button">
										</div>
										<div class="cart-item-price">
											<a ><s>¥{{ food.price }}</s></a>
											<a><strong>¥{{ (food.discount).toFixed(2) }}</strong></a>
										</div>
									</li>
								</ul>
								<div style="text-align: right; margin-top: 10px;">
									总数量: {{ totalCount }}
									总金额: {{ totalPrice | showPrice }}
									<input type="button" @click="order()" value="下单" class="cart-button">
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>

			<!--左侧购物车或订单展示结束  -->
		</div>
	</div>
</div>
    <script src="../js/bootstrap.js"></script>
</body>
<script >
	let app = new Vue({
		el: '#app', // 或者根据你的需求指定一个更大的范围的选择器，比如 '#app'
		data: {
			foods: [],//所有食品信息
			foodType: [],//食物类型如热菜,凉菜
			items: [],//购物车中的菜品信息
			totalCount: 0,//购物车总数量
			totalPrice: 0,//购物车总价格
			dinnerTableId:0,//餐桌号
			foodTypeId:1,//食物类型id
			userid:0,

		},
		methods: {
			fetchFoods() {
				axios.post("../food")
						.then(resp => {
							this.foods = resp.data;
							console.log(this.foods);
						})
						.catch(error => {
							console.error('Error fetching foods:', error);
						});
			},
			fetchFoodType() {
				axios.post("../foodType")
						.then(resp => {
							this.foodType = resp.data;
							console.log(this.foodType);
						})
						.catch(error => {
							console.error('Error fetching food types:', error);
						});
			},
			updateOrderList(){
				axios.post("../OrderList",{
					//订单编码
					//餐桌号
					dinnerTableId:this.dinnerTableId,
					//总价
					totalPrice:this.totalPrice,
					//购物车的菜品信息数据
					items:this.items,
					userid:this.userid
				}).then(res=>{
					console.log(res.data);
				}).catch(error =>{
					console.log("数据获取失败");
				})
			},

			addToCart(foodId) {
				let food = this.foods.find(f => f.id === foodId);
				if (food) {
					this.totalCount++;
					this.totalPrice += food.price * food.discount;
					let existingItem = this.items.find(item => item.id === food.id);
					if (existingItem) {
						existingItem.count++;
					} else {

						this.items.push({
							id: food.id,
							name: food.food_name,
							price: food.price,
							discount: food.discount*food.price,
							count: 1
						});
					}
				}
				console.log(this.items);
			},
			subCount(food) {
				if (food.count > 0) {
					this.totalCount--;
					this.totalPrice -= food.discount;
					food.count--;
				}
				if (food.count === 0) {
					this.items = this.items.filter(item => item.id !== food.id);
				}
			},

			addCount(food) {

				this.totalCount++;
				this.totalPrice += food.discount;
				food.count+=1;
			},
			removeItem(food){
				this.totalPrice-=food.discount*food.count;
				this.totalCount-=food.count;
				this.items = this.items.filter(item => item.id !== food.id);

			},
			order(){
				if (confirm("是否确认下单？")) {
					// 更新订单
					this.updateOrderList();

					// 生成一个唯一的时间戳
					var timestamp = new Date().getTime();

					// 使用时间戳作为查询参数来强制刷新页面
					window.location.href = "../html/orderList.html?timestamp=" + timestamp;
					this.occupancy();

				} else {
					console.log("用户取消了下单操作");
				}
			},
			fooddetail(foodid){
				//发送数据
				sessionStorage.setItem("foodid",foodid);
			},
			getDinnerId(){
				this.dinnerTableId=sessionStorage.getItem('dinnerTableId');
			},
			getUserId() {
				const userIdStr = sessionStorage.getItem("userid");
				if (userIdStr !== null) {
					this.userid = parseInt(userIdStr);
				} else {
					// 处理用户未登录时的逻辑，例如跳转到登录页面或者设置默认值
					this.userid = 0; // 设置默认值为0或者其他合适的未登录状态值
				}
			},

			updateTypeId(TypeId){
				this.foodTypeId=TypeId;
				console.log(this.foodTypeId);
			},
			handleVisibilityChange() {
				if (document.visibilityState === 'hidden') {
					// 用户离开了当前页面
					alert('用户离开页面');
					// 可以执行相应的操作
					this.release();
				} else {
					// 用户回到了当前页面
					console.log('用户回到页面');
					// 可以执行相应的操作
				}
			},
			occupancy(){
				this.getDinnerId();
				const params=new URLSearchParams();
				params.append("tableid",this.dinnerTableId)
				axios.post("../fooddetail?op=occupancy",params).then(resp=>{
					const jm=resp.data;
					if (jm.code===1){
						console.log("占用成功");
					}else {
						console.log("占用失败");
					}
				})
			},
			release(){
				this.getDinnerId();
				const params=new URLSearchParams();
				params.append("tableid",this.dinnerTableId)
				axios.post("../fooddetail?op=release",params).then(resp=>{
					const jm=resp.data;
					if (jm.code===1){
						console.log("释放成功");
					}else {
						console.log("释放失败");
					}
				})
			},
			releaseOnLinkClick(event) {
				// 在超链接点击时执行释放操作
				console.log('超链接被点击');
				this.release();
			},


		},
		filters: {
			//对函数的参数进行过滤
			showPrice(price) {
				if (price==="-0.00"){
					return '￥' +"0.00";
				}else {
					return '￥' + price.toFixed(2);
				}


			},
			showTable(table){
				if (table!==null){
					return table+"号餐桌的购物车";
				}else {
					return '暂未选择座位';
				}
			}
		},

			computed: {
				filteredFoods() {
					if (!this.foodTypeId) {
						return this.foods; // 如果 foodTypeId 为空，则返回所有菜品
					} else {
						return this.foods.filter(food => food.foodtype_id === this.foodTypeId);
					}
				},
				topSellingFoods() {
					// 按销量排序并获取前五的菜品，同时包括排名信息
					return this.foods
							.sort((a, b) => b.totalbuynum - a.totalbuynum)
							.slice(0, 5)
							.map((food, index) => ({ id: food.id, rank: index + 1 }));
				},

			},
		mounted() {
			this.fetchFoods();//拿到食品信息
			this.fetchFoodType();//拿到食品类型信息
			this.getDinnerId();//拿到餐桌的id
			this.getUserId();//拿到用户的id

			const links = document.querySelectorAll('a');

			links.forEach(link => {
				link.addEventListener('click', this.releaseOnLinkClick);
			});


		},
		beforeDestroy() {


		},
		beforeUnmount() {
			// 组件即将销毁时执行的操作
			console.log('组件即将销毁');

			const links = document.querySelectorAll('a');

			links.forEach(link => {
				link.removeEventListener('click', this.releaseOnLinkClick);
			});


		},
	});


</script>
</html>